package com.petrochina.cloudconfig.util;

import com.alibaba.fastjson.JSON;
import com.petrochina.cloudconfig.domain.DeployServer;
import com.petrochina.cloudconfig.domain.Server;
import org.springframework.beans.BeanUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.FileSystems;
import java.nio.file.Files;

/**
 * server util
 */
public class ServerUtil {

    /**
     * set server info
     * @param deployServer
     */
    public static void setServerInfo(DeployServer deployServer,String serverRootPath) {
        String serverIp = deployServer.getServerIp();
        try {
            byte[] bytes = Files.readAllBytes(FileSystems.getDefault().getPath(serverRootPath+ File.separator+serverIp+".json"));
            Server server = JSON.parseObject(new String(bytes, "gbk"), Server.class);
            if(server != null){
                BeanUtils.copyProperties(server,deployServer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * check up can connect
     * @param ip
     * @return
     */
    public static boolean checkIpCanConn(String ip){
        try {
            InetAddress inetAddress = InetAddress.getByName(ip);
            return inetAddress.isReachable(500);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
